#include "formcharts.h"
#include "ui_formcharts.h"

FormCharts::FormCharts(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormCharts)
{
    ui->setupUi(this);

    max_size = 20;

    chart = new QChart();
    chart->setMargins(QMargins(0,0,0,0));
    chart->setTitle("");
    chart->legend()->hide();

    series_rpm_left = new QSplineSeries(chart);
    series_rpm_left->setUseOpenGL(true);
    QPen pen;
    pen.setWidth(3);
    pen.setColor(QColor(115, 210, 22));
    series_rpm_left->setPen(pen);
    chart->addSeries(series_rpm_left);

    series_rpm_right = new QSplineSeries(chart);
    pen.setColor(QColor(52, 101, 164));
    series_rpm_right->setPen(pen);
    series_rpm_right->setUseOpenGL(true);
    chart->addSeries(series_rpm_right);

    for(int i=0; i<max_size; i++)
    {
        series_rpm_left->append(i,0);
        series_rpm_right->append(i,0);
    }

    chart->createDefaultAxes();
    chart->axisX()->setRange(0, max_size);
    chart->axisX()->hide();
    chart->axisY()->setRange(-2500, 2500);
    chart->axisY()->hide();
    // Add space to label to add space between labels and axis
    //static_cast<QValueAxis *>(chart->axisY())->setLabelFormat("%500  ");
    chart_view = new QChartView(chart);
    chart_view->chart()->setBackgroundBrush(QBrush(QColor(36,36,36)));
    ui->verticalLayout_2->addWidget(chart_view);

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout,this,&FormCharts::timerUpdate);
    timer->start(100);
}

FormCharts::~FormCharts()
{
    delete ui;
    delete series_rpm_left;
    delete series_rpm_right;
    delete chart;
    delete chart_view;
}

void FormCharts::timerUpdate(void)
{
    QVector<QPointF> rpm_left_oldpoints = series_rpm_left->pointsVector();
    QVector<QPointF> rpm_left_points;
    for(int i=1;i<max_size;++i)
    {
        rpm_left_points.append(QPointF(i-1, rpm_left_oldpoints.at(i).y()));
    }
    rpm_left_points.push_back(QPointF(max_size,ui->label->text().toInt()));
    series_rpm_left->replace(rpm_left_points);

    QVector<QPointF> rpm_right_oldpoints = series_rpm_right->pointsVector();
    QVector<QPointF> rpm_right_points;
    for(int i=1;i<max_size;++i)
    {
        rpm_right_points.append(QPointF(i-1, rpm_right_oldpoints.at(i).y()));
    }
    rpm_right_points.push_back(QPointF(max_size,ui->label_2->text().toInt()));
    series_rpm_right->replace(rpm_right_points);
}

void FormCharts::setLeftRPM(int value)
{
    ui->label->setText(QString::number(value));
}

void FormCharts::setRightRPM(int value)
{
    ui->label_2->setText(QString::number(value));
}
